/*** Eclipse Class Decompiler plugin, copyright (c) 2012 Chao Chen (cnfree2000@hotmail.com) ***/
package com.kingdee.eas.qx.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.Locale;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.framework.session.BOSLoginException;
import com.kingdee.bos.framework.session.LoginContext;
import com.kingdee.bos.framework.session.LoginModuleFactory;
import com.kingdee.bos.framework.session.SessionInfo;
import com.kingdee.bos.framework.session.SessionManager;
import com.kingdee.bos.util.CryptException;
import com.kingdee.bos.util.CryptoTean;
import com.kingdee.eas.util.ExceptionUtil;

public class ContextHolder {
	private static Logger logger = Logger.getLogger(ContextHolder.class);

	private static Locale LOCALE = new Locale("L2");

	private static Context ctx = null;

	public static synchronized Context getContext() throws BOSLoginException,
			BOSException, SQLException {
		if (ctx == null) {
			login();
		} else {
			SessionInfo session = SessionManager.getInstance().getSession(
					ctx.getContextID());
			if (session == null) {
				login();
			}
		}

		return ctx;
	}

	private static void login() throws BOSLoginException, BOSException, SQLException {
		Properties pro = new Properties();
		String propertie = "com/kingdee/eas/qx/util/oms.properties";
		InputStream ins = OmsUtil.class.getClassLoader().getResourceAsStream(propertie);
		try {
			pro.load(ins);
		} catch (IOException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		String userName = (String)pro.get("userName");
		String pwd = (String)pro.get("pwd");
		String dbId = (String)pro.get("dbId");
		String encodePwd = encodePassword(userName,pwd);
		LoginContext loginCtx = new LoginContext(userName,encodePwd, "eas", dbId, LOCALE);
		ctx = LoginModuleFactory.getLocalInstance(null).fullLogin(loginCtx);
	}

	private static String encodePassword(String userName, String password) {
		String encodedPassword = "";
		try {
			encodedPassword = CryptoTean.encrypt(userName, password);
		} catch (CryptException e) {
			logger.error(ExceptionUtil.getExcLinkStackTrace(e));
		}

		return encodedPassword;
	}
}